//
//  UpdataImageManager.m
//  Campus
//
//  Created by Hancong on 15/1/20.
//  Copyright (c) 2015年 hzyd. All rights reserved.
//

#import "UpLoadImageManager.h"
#import "SVProgressHUD.h"
#import "SDWebImageManager.h"


@implementation UpLoadImageManager

+(void)uploadImage:(UIImage *)image uploadImageURL:(NSString *)imageUrl withCompltedBlock:(void (^)(BOOL success,NSString *urlString))block
{
    NSString *userid = [[NSUserDefaults standardUserDefaults]objectForKey:KUserDefaultsUserIdKey];
    [[NSUserDefaults standardUserDefaults]synchronize];
    /**
     *  上传图片
     *
     */
    NSData *data = UIImageJPEGRepresentation(image, 0.1f);
    
    NSString *TWITTERFON_FORM_BOUNDARY = @"0xKhTmLbOuNdArY";
    NSString * postUrl = @"";
    
    //根据url初始化request
    if([imageUrl isEqualToString:KUpLoadPicInterface])
    {
        postUrl = [NSString stringWithFormat:@"%@&uid=%@",imageUrl,userid];
    }else if ([imageUrl isEqualToString:KWashCarImageInterface])
    {
        postUrl = [NSString stringWithFormat:@"%@",imageUrl];
    }

    NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:postUrl]
                                                           cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
                                                       timeoutInterval:10];
    //分界线 --AaB03x
    NSString *MPboundary=[[NSString alloc]initWithFormat:@"--%@",TWITTERFON_FORM_BOUNDARY];
    //结束符 AaB03x--
    NSString *endMPboundary=[[NSString alloc]initWithFormat:@"%@--",MPboundary];
    //得到图片的data

    data = UIImageJPEGRepresentation(image, 0.1f);
    //http body的字符串
    NSMutableString *body=[[NSMutableString alloc]init];
    
    //    if(picFilePath){
    ////添加分界线，换行
    [body appendFormat:@"%@\r\n",MPboundary];
    
    //声明pic字段，文件名为boris.png
    [body appendFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"%@\"\r\n",@"washcar",@"currentImage.jpg"];
    //声明上传文件的格式
    [body appendFormat:@"Content-Type: image/jpge,image/gif, image/jpeg, image/pjpeg, image/pjpeg\r\n\r\n"];
    //    }
    //    NSLog(@"body = %@",body);
    
    //声明结束符：--AaB03x--
    NSString *end=[[NSString alloc]initWithFormat:@"\r\n%@",endMPboundary];
    //声明myRequestData，用来放入http body
    NSMutableData *myRequestData=[NSMutableData data];
    
    //将body字符串转化为UTF8格式的二进制
    [myRequestData appendData:[body dataUsingEncoding:NSUTF8StringEncoding]];
    //    if(picFilePath){
    //将image的data加入
    [myRequestData appendData:data];
    //    }
    //加入结束符--AaB03x--
    [myRequestData appendData:[end dataUsingEncoding:NSUTF8StringEncoding]];
    
    //设置HTTPHeader中Content-Type的值
    NSString *content=[[NSString alloc]initWithFormat:@"multipart/form-data; boundary=%@",TWITTERFON_FORM_BOUNDARY];
    //设置HTTPHeader
    [request setValue:content forHTTPHeaderField:@"Content-Type"];
    //设置Content-Length
    [request setValue:[NSString stringWithFormat:@"%ld", [myRequestData length]] forHTTPHeaderField:@"Content-Length"];
    NSLog(@"Length = %ld",[myRequestData length]);
    
    //设置http body
    [request setHTTPBody:myRequestData];
    //http method
    [request setHTTPMethod:@"POST"];
    //    request set
    
    __block NSString *postImageUrl;
    [SVProgressHUD showWithStatus:@"正在获取图片..."];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0), ^{
        NSHTTPURLResponse *urlResponese = nil;
        NSError *error = [[NSError alloc]init];
        NSData* resultData = [NSURLConnection sendSynchronousRequest:request   returningResponse:&urlResponese error:&error];
//        NSLog(@"%@",request);
        if (resultData) {
            NSDictionary *dicData=[NSJSONSerialization JSONObjectWithData:resultData options:NSJSONReadingMutableLeaves error:nil ];
            dispatch_async(dispatch_get_main_queue(), ^{
                NSString *str = [NSString stringWithFormat:@"%@",dicData[@"status"]];
                if([str isEqualToString:@"1"])
                {
                    
                    //根据url初始化request
                    if([imageUrl isEqualToString:KUpLoadPicInterface])
                    {
                        postImageUrl = [NSString stringWithFormat:@"%@",dicData[@"headimgurl"]];
                    }else if ([imageUrl isEqualToString:KWashCarImageInterface])
                    {
                        postImageUrl = [NSString stringWithFormat:@"%@",dicData[@"imageUrl"]];
                    }
                    
                    [[SDWebImageManager sharedManager] saveImageToCache:image forURL:[NSURL URLWithString:postImageUrl]];
                    
                    if (block) {
                        block(YES,postImageUrl);
                    }
                }else{
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [SVProgressHUD showErrorWithStatus:@"上传失败"];
                        postImageUrl = @"";
                        
                        if (block) {
                            block(NO,postImageUrl);
                        }
                    });
                }
                [SVProgressHUD dismiss];
                
            });
        }else{
            dispatch_async(dispatch_get_main_queue(), ^{
                [SVProgressHUD showErrorWithStatus:@"上传失败"];
                postImageUrl = @"";
                if (block) {
                    block(NO,postImageUrl);
                }
            });
        }
    });
}

+(void)uploadVideo:(NSData *)data uploadVideoURL:(NSString *)videoUrl withCompltedBlock:(void (^)(BOOL success, NSString *respond))block
{
    NSString *TWITTERFON_FORM_BOUNDARY = @"0xKhTmLbOuNdArY";

    //分界线 --AaB03x
    NSString *MPboundary=[[NSString alloc]initWithFormat:@"--%@",TWITTERFON_FORM_BOUNDARY];
    //结束符 AaB03x--
    NSString *endMPboundary=[[NSString alloc]initWithFormat:@"%@--",MPboundary];
    //得到图片的data
    
//    data = UIImageJPEGRepresentation(image, 0.1f);
    //http body的字符串
    NSMutableString *body=[[NSMutableString alloc]init];
    
    //    if(picFilePath){
    ////添加分界线，换行
    [body appendFormat:@"%@\r\n",MPboundary];
    
    //声明pic字段，文件名为boris.png
    [body appendFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"%@\"\r\n",@"file",@"currentVideo.mp3"];
    
    //声明上传文件的格式
    [body appendFormat:@"Content-Type: video/mp4,video/mp3\r\n\r\n"];
    
    //    NSLog(@"body = %@",body);
    
    //声明结束符：--AaB03x--
    NSString *end=[[NSString alloc]initWithFormat:@"\r\n%@",endMPboundary];
    //声明myRequestData，用来放入http body
    NSMutableData *myRequestData=[NSMutableData data];
    
    //将body字符串转化为UTF8格式的二进制
    [myRequestData appendData:[body dataUsingEncoding:NSUTF8StringEncoding]];
    
    [myRequestData appendData:data];
    
    //加入结束符--AaB03x--
    [myRequestData appendData:[end dataUsingEncoding:NSUTF8StringEncoding]];
    
    //设置HTTPHeader中Content-Type的值
    NSString *content=[[NSString alloc]initWithFormat:@"multipart/form-data; boundary=%@",TWITTERFON_FORM_BOUNDARY];

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:videoUrl]];
    [request setHTTPMethod:@"POST"];
    [request setValue:content forHTTPHeaderField:@"Content-Type"];
    [request setValue:[NSString stringWithFormat:@"%ld",body.length] forHTTPHeaderField:@"Content-Length"];
    [request setValue:@"no-cache" forHTTPHeaderField:@"Cache-Control"];
    [request setHTTPBody:myRequestData];
    
    __block NSString *postImageUrl;
//    [SVProgressHUD showWithStatus:@"正在获取图片..."];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0), ^{
        NSHTTPURLResponse *urlResponese = nil;
        NSError *error = [[NSError alloc]init];
        NSData* resultData = [NSURLConnection sendSynchronousRequest:request   returningResponse:&urlResponese error:&error];
        NSLog(@"%@",request);
        if (resultData) {
            NSDictionary *dicData=[NSJSONSerialization JSONObjectWithData:resultData options:NSJSONReadingMutableLeaves error:nil ];
            NSLog(@"%@",dicData);
            dispatch_async(dispatch_get_main_queue(), ^{
                if([dicData[@"status"] boolValue])
                {
                    postImageUrl = [NSString stringWithFormat:@"%@",dicData[@"file_url"]];
                    //                    _postUrl = [NSString stringWithFormat:@"%@",dicData[@"data"][0]];
//                    [[SDWebImageManager sharedManager] saveImageToCache:image forURL:[NSURL URLWithString:postImageUrl]];
                    
                    if (block) {
                        block(YES,postImageUrl);
                    }
                }else{
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [SVProgressHUD showErrorWithStatus:@"上传失败"];
                        postImageUrl = @"";
                        
                        if (block) {
                            block(NO,postImageUrl);
                        }
                    });
                }
                [SVProgressHUD dismiss];
                
            });
        }else{
            dispatch_async(dispatch_get_main_queue(), ^{
                [SVProgressHUD showErrorWithStatus:@"上传失败"];
                postImageUrl = @"";
                if (block) {
                    block(NO,postImageUrl);
                }
            });
        }
    });

}

@end
